package redis

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"server/pkg/log"
	"time"
)

type Redis struct {
	Host   string `json:"host"`
	Port   int64  `json:"port"`
	Object *redis.Client
}

func InitRedis(host string, port int64, password string) *Redis {
	return &Redis{
		Host: host,
		Port: port,
		Object: redis.NewClient(&redis.Options{
			Addr:     fmt.Sprintf("%s:%d", host, port),
			Password: password,
			DB:       0,
			PoolSize: 50,
		}),
	}
}

func (r *Redis) Set(key, val string, expr int64) (string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	v, err := r.Object.Ping(ctx).Result() // 检查连接redis是否成功
	if err != nil {
		log.Error("[redis]: set \n", err, v)
		return v, err
	}
	return "", r.Object.Set(ctx, key, val, time.Second*time.Duration(expr)).Err()
}

func (r *Redis) Get(key string) (string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	v, err := r.Object.Ping(ctx).Result() // 检查连接redis是否成功
	if err != nil {
		log.Error("[redis]: get  \n", err, v)
		return v, err
	}
	val := r.Object.Get(ctx, key)
	return val.Val(), val.Err()
}

func (r *Redis) Del(key string) (int64, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	v, err := r.Object.Ping(ctx).Result() // 检查连接redis是否成功
	if err != nil {
		log.Error("[redis]: del  \n", err, v)
		return 0, err
	}
	return r.Object.Del(ctx, key).Result()
}
